import 'dart:io';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:flutter/material.dart';

class DataBaseUtil {
  static String _create_novel =
      "CREATE TABLE IF NOT EXISTS Novel ( id INTEGER PRIMARY KEY, "
      "authorId TEXT, "
      "authorName TEXT, "
      "bookName TEXT, "
      "bid TEXT,"
      "cid TEXT, "
      "bookCover TEXT, "
      "className TEXT, "
      "bookInfo TEXT)";

  //id,createdAt,desc,source,who,type,publishedAt,url
  static String _create_image =
      "CREATE TABLE IF NOT EXISTS Meitu ( id INTEGER PRIMARY KEY, "
      "createdAt TEXT, "
      "desc TEXT, "
      "source TEXT,"
      "who TEXT, "
      "type TEXT, "
      "publishedAt TEXT, "
      "url TEXT)";

  static String _dataBaseName = "novel.db";

  static DataBaseUtil _dataBase;

  Database _database;

  String db_path="";

  static DataBaseUtil getInstance() {
    if (_dataBase == null) {
      _dataBase = DataBaseUtil();
    }
    return _dataBase;
  }

  void createDataBase() async {
    var data = await getDatabasesPath();
    String path = join(data, _dataBaseName);
    print(path);
    if (await Directory(dirname(path)).exists()) {
      _database = await openDatabase(path, version: 1,
          onCreate: (Database database, int v) async {
        print("**************   $v");
        db_path=path;
        create(database);
      },onOpen: (Database database){
            create(database);
          });
    } else {
      Directory(dirname(path)).create(recursive: false).then((value) async {
        _database = await openDatabase(path, version: 1,
            onCreate: (Database database, int v) async {
          print("+++++++++++      $value");
          db_path=path;
          create(database);
        },onOpen: (Database database){
              create(database);
            });
      });
    }

  }

  Database getDataBase() {
    return _database;
  }

  void create(Database database)async{
    await database.execute(_create_novel);
    await database.execute(_create_image);
  }

}
